package com.zjweu.hkg.Controller;
import com.zjweu.hkg.DTO.ArticleViewHistoryDTO;
import com.zjweu.hkg.DTO.ArticleWithTagsDTO;
import com.zjweu.hkg.POJO.ArticleTags;
import com.zjweu.hkg.POJO.ArticleViewHistory;
import com.zjweu.hkg.POJO.Result;
import com.zjweu.hkg.POJO.Tag;
import com.zjweu.hkg.Servies.ArticleService;
import com.zjweu.hkg.Servies.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    @Autowired
    FileService fileService;
    // 历史记录数量阈值，可根据实际情况调整
    private static final int HISTORY_COUNT_THRESHOLD = 10;
    // tag 比例阈值，可根据实际情况调整
    private static final double TAG_RATIO_THRESHOLD = 0.3;
    @RequestMapping("/addArticle")
    public Result<Integer> addArticle(@RequestBody Map<String, Object> requestData){
        System.out.println("发来文章了！");
        return articleService.addArticle(requestData);
    }
    @PostMapping("/uploadArticleImage")
    public ResponseEntity<String> uploadArticleImage(@RequestParam("file") MultipartFile file, String userName, String articleUUID){
        System.out.println("发来图片了！");
        return articleService.uploadArticleImage(file,userName,articleUUID);
    }
    @PostMapping("/getAllArticleWithTags")
    public List<ArticleWithTagsDTO> getAllArticleWithTags(@RequestBody Map<String, Object> requestData) {
        int userId = (int) requestData.get("userId");
        // 获取用户的文章浏览历史记录
        List<ArticleViewHistory> historyList = articleService.getArticleViewHistoryByUserId(userId);

        if (historyList.size() < HISTORY_COUNT_THRESHOLD) {
            // 历史记录数量少，返回全部文章
            return articleService.getAllArticleWithTags();
        }
        //截取最近10条记录
        historyList = historyList.subList(Math.max(historyList.size() - HISTORY_COUNT_THRESHOLD, 0), historyList.size());
        // 用于存储每个 tag 的点击次数
        Map<String, Integer> tagCountMap = new HashMap<>();
        int totalCount = 0;

        // 遍历历史记录，统计每个 tag 的点击次数
        for (ArticleViewHistory history : historyList) {
            int articleId = history.getArticleId();
            List<ArticleTags> articleTagsList = articleService.findArticleTagsByArticleId(articleId);

            for (ArticleTags articleTags : articleTagsList) {
                int tagId = articleTags.getTagId();
                Tag tag = articleService.findTagsByTagId(tagId);
                if (tag != null) {
                    String tagContent = tag.getTagContent();
                    tagCountMap.put(tagContent, tagCountMap.getOrDefault(tagContent, 0) + 1);
                    totalCount++;
                }
            }
        }

        // 筛选出比例高于阈值的 tag
        List<String> recommendedTags = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : tagCountMap.entrySet()) {
            double ratio = (double) entry.getValue() / totalCount;
            if (ratio > TAG_RATIO_THRESHOLD) {
                recommendedTags.add(entry.getKey());
            }
        }

        if (recommendedTags.isEmpty()) {
            // 没有符合条件的 tag，返回全部文章
            return articleService.getAllArticleWithTags();
        }
        System.out.println("推荐recommendedTags = " + recommendedTags);
        // 根据 tag 获取推荐文章
        List<ArticleWithTagsDTO> recommendedArticles = articleService.getArticlesByTags(recommendedTags);

        // 根据 tag 点击量对推荐文章进行排序
        recommendedArticles.sort((a1, a2) -> {
            int score1 = 0;
            int score2 = 0;
            for (String tag : a1.getTagNames()) {
                score1 += tagCountMap.getOrDefault(tag, 0);
            }
            for (String tag : a2.getTagNames()) {
                score2 += tagCountMap.getOrDefault(tag, 0);
            }
            return score2 - score1;
        });
        System.out.println("推荐的文章："+recommendedArticles);
        return recommendedArticles;
    }

    @PostMapping("/getArticleWithTagsByArticleId")
    public ArticleWithTagsDTO getArticleWithTagsByArticleId(@RequestBody Map<String, Object> requestData){

            System.out.println("根据文章id查找文章，带tag");
            int articleId=Integer.parseInt((String) requestData.get("articleId"));
            int uid= (int) requestData.get("userId");
            return articleService.getArticleWithTagsByArticleId(articleId,uid);
    }
    @PostMapping("/getAllArticleWithTagsByUserId")
    List<ArticleWithTagsDTO> getAllArticleWithTagsByUserId(@RequestBody Map<String, Object> requestData){
        System.out.println("userId的类型是："+requestData.get("userId").getClass());
        System.out.println(requestData.get("userId") instanceof String);
        int userId=-1;
        //判断用户ID是否为字符串类型，并转换为int类型
        if(requestData.get("userId") instanceof String){
            userId=Integer.parseInt((String) requestData.get("userId"));
        }else{
            userId= (int) requestData.get("userId");
        }

        return articleService.getAllArticleWithTagsByUserId(userId);
    }

    @PostMapping("/updateArticleWithTagsByArticleId")
    public Result<Integer> updateArticleWithTagsByArticleId(@RequestBody Map<String, Object> requestData){
        System.out.println("发来文章了！");
        ArticleWithTagsDTO articleWithTagsDTO=articleService.getArticleWithTagsByArticleId(Integer.parseInt((String) requestData.get("articleId")));
        articleWithTagsDTO.getArticle().setArticleTitle((String) requestData.get("articleTitle"));
        articleWithTagsDTO.getArticle().setArticleContent((String) requestData.get("articleContent"));
        articleWithTagsDTO.setTagNames((List<String>) requestData.get("tag"));
        articleWithTagsDTO.getArticle().setPermission((int) requestData.get("permission"));
        return articleService.updateArticleWithTagsByArticleId(articleWithTagsDTO);
    }
    @PostMapping("/deleteArticleByArticleId")
    public Result<String> deleteArticleByArticleId(@RequestBody Map<String, Object> requestData){
        int articleId= (int)requestData.get("articleId");
        return articleService.deleteArticleByArticleId(articleId);
    }
    @PostMapping("/createArticleUUID")
    public Result<String> createArticleUUID(){
       return Result.success(String.valueOf(UUID.randomUUID()));
    }

    //增加文章浏览记录
    @PostMapping("/addArticleViewHistory")
   public Result<String> addArticleViewHistory(@RequestBody Map<String, Object> requestData){
        int articleId= Integer.parseInt((String) requestData.get("articleId"));
        int uid= (int) requestData.get("userId");
        int result= articleService.addArticleViewHistory(articleId,uid);
        return result==1?Result.success("增加文章浏览记录成功"):Result.error("增加文章浏览记录失败");
    };
    @PostMapping("/findArticleViewHistoryByUserId")
    List<ArticleViewHistoryDTO> findArticleViewHistoryByUserId(@RequestBody Map<String, Object> requestData){
        int userId= (int) requestData.get("userId");
        return articleService.findArticleViewHistoryByUserId(userId);
    };

    @PostMapping("/likeSearchArticleByName")
    public List<ArticleWithTagsDTO> likeSearchArticleByName(@RequestBody Map<String, Object> requestData){
        String articleTitle= (String) requestData.get("articleTitle");
        List<ArticleWithTagsDTO> articleWithTagsDTOS=articleService.likeSearchArticleByName(articleTitle);
        System.out.println("搜索到的文章= " + articleWithTagsDTOS);
        return articleWithTagsDTOS;
    }
    @PostMapping("/getFollowedArticles")
    public Result<List<ArticleWithTagsDTO>> getFollowedArticles(@RequestBody Map<String, Object> requestData){
        int userId= (int) requestData.get("userId");
        List<ArticleWithTagsDTO> articleWithTagsDTOS=articleService.getFollowedArticles(userId);
        //按时间倒序排列
        articleWithTagsDTOS.sort((a1, a2) -> a2.getArticle().getCreateDate().compareTo(a1.getArticle().getCreateDate()));
        System.out.println("已关注人的文章= " + articleWithTagsDTOS);
        return Result.success(articleWithTagsDTOS);
    }
}
